#include "HashMap.h"
#include <iostream>


 HashMap::HashMap(int HashSize)
 {  
    this->HashSize = HashSize;
    array = new Node*[HashSize];
    for(int i = 0;i < HashSize;i++)
    {
        array[i] = nullptr;
    }
 }

HashMap::~HashMap()
{
    for(int i = 0;i < HashSize;i++)
    {
        Node *node = array[i];
        while(node != nullptr)
        {
            Node *temp = node->next;
            delete node;
            node = temp;
        }
    }
    delete []array;
}

int HashMap::Hash(const std::string &key)
{   
    int hash = 0;
    for(int i =  0;i < key.size();i++)
    {
        hash = (hash*31 + key[i])%HashSize;
    }
    //把每一个字母的ascii值 加起来 把和*素数
    return hash;
}

void HashMap::Insert(const std::string &key, ElementType value)
{
    Node *node = new Node(key,value);
    int index = Hash(key);
   
   
    if(array[index] == nullptr)
        array[index] = node;
    else
    {   
        //头插
        node->next = array[index];
        array[index] = node;

    }
}
ElementType *HashMap::Get(const std::string &key)
{
    Node* node = array[Hash(key)];
    if(node == nullptr)
        return nullptr;
    while(node != nullptr)
    {
        if(node->key == key)
            return &node->data;
        node = node->next;
    }
    return nullptr;
}

void HashMap::show()
{
    for(int i = 0;i < HashSize;i++)
    {
        Node *node = array[i];
        while(node != nullptr)
        {
            std::cout<<"key|"<<node->key<<"|hash|"<<Hash(node->key)<<"|value|"<<node->data<<"|"<<std::endl;
            node = node->next;
        }
    }
}

ElementType& HashMap::operator[](const std::string &key)
{   
    ElementType*data = Get(key);
    if(data)
        return *data;
    else
    {
        // Insert(key,0);
        Insert(key,0);
        return *Get(key);
    }
}

void HashMap::Remove(const std::string &key)
{
    for(int i = 0;i < HashSize;i++)
    {
        Node *node = array[i];
        if(node == nullptr)
            continue;
        if(node->key == key)
        {
            array[i] = node->next;
            delete node;
            return;
        }
        while(node->next != nullptr)
        {
            if(node->next->key == key)
            {
                Node* temp = node->next;
                node->next = node->next->next;
                delete temp;
                return;
            }
            node = node->next;
        }
    }
}

void HashMap::showBykey()
{
    for(int i = 0;i < HashSize;i++)
    {
        Node *node = array[i];
        if(node == nullptr)
            continue;
        while(node != nullptr)
        {
           std::cout<<node->data<<" ";
           node = node->next;
        }
        std::cout<<std::endl;
    }
}
